package com.soft.springhrms.controller;

import com.soft.springhrms.pojo.Attendance;
import com.soft.springhrms.pojo.SystemLogs;
import com.soft.springhrms.pojo.Users;
import com.soft.springhrms.service.AttendanceService;
import com.soft.springhrms.service.SystemLogsService;
import com.soft.springhrms.service.UsersService;
import com.soft.springhrms.utils.IPUtil;
import com.soft.springhrms.utils.JwtUtil;
import com.soft.springhrms.utils.MD5Util;
import com.soft.springhrms.vo.ResultVO;
import com.soft.springhrms.vo.UsersVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@RequestMapping("/users")
@RestController
@CrossOrigin
public class UsersController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private AttendanceService attendanceService;
    @Autowired
    private SystemLogsService systemLogsService;

    @PostMapping("/register")
    public ResultVO register(@RequestBody Users users) {
        try {
            usersService.addUser(users);
            return ResultVO.success("注册成功", "注册成功");
        } catch (RuntimeException e) {
            return ResultVO.error(404, "注册失败" + e.getMessage());
        }
    }

    @PostMapping("/login")
    public ResultVO login(@RequestBody Users users, HttpServletRequest request) {
        String phoneNumber = users.getPhoneNumber();
        String password = users.getEncryptedPassword();
        // 使用 MD5 对密码进行加密
        String md5Password = MD5Util.encrypt(password);  // 使用 MD5 加密密码
        // 根据手机号和加密后的密码查找用户
        UsersVO user = usersService.findByPhoneNumber(phoneNumber, md5Password);
        if (user == null) {
            return ResultVO.error(404, "电话号码或密码错误!");
        }
        // 生成 JWT Token
        String token = JwtUtil.generateToken(user.getUserName(), user.getId(), user.getRoleId());
        // 记录登录日志
        SystemLogs systemLogs = new SystemLogs();
        systemLogs.setUserId(user.getId());
        systemLogs.setLogTime(new Date());
        systemLogs.setIpAddress(IPUtil.getClientIp(request));
        systemLogsService.saveLogs(systemLogs);

        // 返回包含 Token 和用户信息的结果
        return ResultVO.successWithToken(token, user);
    }

    @GetMapping("/{id}")
    public Users getUser(@PathVariable Integer id){
        return usersService.getById(id);
    }
    @PostMapping("/verify-password")
    public Boolean judgePassword(@RequestParam Integer id,@RequestParam String oldPassword){
        String md5Password = MD5Util.encrypt(oldPassword);
        String realPassword= usersService.getById(id).getEncryptedPassword();
        System.out.println(md5Password);
        System.out.println(realPassword);
        if (md5Password != null) {
            System.out.println(md5Password.equals(realPassword));
            return md5Password.equals(realPassword);
        }
        return false;
    }
    @PutMapping("/update/{id}")
    public ResultVO updateUser(@RequestBody Map<String, Object> request, @PathVariable Integer id){
            // 从 Map 中提取数据
            Map<String, Object> userInfo = (Map<String, Object>) request.get("userInfo");
            String newPassword = (String) request.get("newPassword");
            Users user=new Users();
            user.setId(id);
            user.setUpdatedAt(new Date());
            user.setUsername((String) userInfo.get("username"));
            user.setEmail((String) userInfo.get("email"));
            // 检查字符串是否为空
        try {
            if (newPassword == null || newPassword.isEmpty()) {
                // 字符串为空时的响应
                usersService.updateById(user);
                return ResultVO.success("更新用户信息成功","更新用户信息成功");
            } else {
                // 字符串不为空时的响应
                user.setEncryptedPassword(MD5Util.encrypt(newPassword));
                usersService.updateById(user);
                return ResultVO.success("更新用户信息和密码成功","更新用户信息和密码成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.error(500,"服务器错误");
        }
    }

    @GetMapping("/test")
    public String testEndpoint() {
        return "This is a test endpoint!";
    }


    @GetMapping("/attendance")
    public Map<String, Object> getUserAttendanceRecords(@RequestParam Integer employeeId,
                                                        @RequestParam(defaultValue = "1") int page,
                                                        @RequestParam(defaultValue = "10") int size) {
        return attendanceService.getUserAttendanceRecords(employeeId, page, size);
    }
    @PostMapping("/clock-in")
    public ResultVO clockIn(@RequestBody Map<String, Integer> requestBody) {
        Integer attendanceId = requestBody.get("attendanceId");
        int success =attendanceService.clockIn(attendanceId);
        return ResultVO.success(success,"打卡成功");
    }
}
